import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { CategoryName } from '../../pipes/categoryNamePipe';
import { Util } from '../../utils/util';
import { Subscription } from 'rxjs/Subscription';
import { CatComponentService } from './cat.component.service';
declare var $: any;
@Component({
    selector: 'ng-cat',
    templateUrl: './cat.component.html',
    styleUrls: ['./cat.component.css'],
    providers: [CatComponentService]
})

export class CatComponent {

    @Input('option') option: any;

    /*Option
  
    cat:any = {}
  
    defaultText:boolean
  
    noLeaf:boolean
  
    onlyLeaf:boolean
  
    placeholder:string
  
    all:boolean
  
    */

    // @Input('data') data:any;


    selects: any = [];


    @Output('onChangeCat') onChangeCat: EventEmitter<any> = new EventEmitter<any>();

    constructor(private service: CatComponentService, private util: Util, private CategoryName: CategoryName) { }


    // emitdata
    emitData = {
        wholeName: "",
        categoryId: "",
        catName: ""
    };


    firstNodeEvent: Subscription;
    ngOnInit() {
        this.selects = [];
        this.selects.length = 0;

        let res = { "code": 0, "msg": "成功", "data": [{ "id": 964, "type": 4, "target": "50019780", "userId": 5, "value": "数码/手机/家电--平板电脑/MID", "createTime": 1508895423000 }] };
        ;

        let _data = this.treeItemInit(res.data);

        _data.active = _data.tree[0];

        this.selects.push(_data);

        console.log(this.selects);
        setTimeout(()=>{
            this.onChangeCat.emit(_data.active);
        },1000);
        
        // this.historyStoreExpand();


    }

    // selects change
    selectChangeTree(data) {
        console.log(data);

        let _active = data['value'];

        console.log(_active);

        this.onChangeCat.emit(_active);


        let select_index = this.arryIndexOf(_active, this.selects);
        console.log("select_index: " + select_index);
        console.log(this.selects.length);
        // 重置selects区域
        let end = Number(select_index) + 1;

        if (end == this.selects.length) {

        } else {
            this.selects = this.selects.slice(0, end);
        }



        if (_active.children === true) {


            this.nodeExpand(_active);
        }

    }

    // 查找数组中的莫一项小标
    arryIndexOf(item, array) {
        let _index: any;

        for (let i in array) {

            let _tree = array[i]['tree'];

            if (_tree.indexOf(item) != -1) {

                _index = i;
                break;
            }
        }

        return _index;
    }

    // Output
    emitDataInit(data) {

        this.emitData.catName = data.catName;

        this.emitData.categoryId = data.categoryId;

        this.emitData.wholeName = data.categoryName;

        this.onChangeCat.emit(this.emitData);
    }


    // treeInit
    treeItemInit(data) {

        let _data: any = [];

        for (let i in data) {

            let item = data[i];

            let _item: any = {};

            let _id = item.target || item.id;

            let _categoryName = item.wholeName || item.value;

            // 没有children
            if (Number(_id) > 0) {

                _item = {
                    level: item.level || 2,
                    catName: this.CategoryName.transform(_categoryName),
                    categoryName: _categoryName,
                    categoryId: _id,
                    children: false
                };

            } else {

                _item = {
                    level: item.level || 2,
                    catName: this.CategoryName.transform(_categoryName),
                    categoryName: _categoryName,
                    categoryId: _id,
                    children: true
                };

            }

            _data.push(_item);
        }

        return {
            tree: _data,
            active: ''
        };
    }

    // 扩展分支，分支定位
    nodeExpandEvent: Subscription;
    /**
     * 
     * @param _item 
     * @param select_index seletcs index 下标
     */
    nodeExpand(_item) {

        let json = {
            catName: _item.categoryName,
            level: _item.level + 1
        };


        console.log(this.selects);
        // expand
        this.nodeExpandEvent = this.service.getExpand(json).subscribe((res: any) => {

            let _data = this.treeItemInit(res.data);

            this.selects.push(_data);
        });
    }





    ngOnDestroy() {
        if (this.firstNodeEvent) {
            this.firstNodeEvent.unsubscribe();
        }



    }
}
